package com.min.main.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.min.common.entity.MinReource;
import com.min.common.util.ShiroUtils;
import com.min.main.constant.UserConst;
import com.min.main.dao.PermissionRoleDao;
import com.min.main.entity.MenuRoleEntity;
import com.min.main.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限对应表
 *
 * @author fengt
 * @date 2021-06-23 11:41:08
 */
@Service
public class MenuRoleService extends ServiceImpl<PermissionRoleDao, MenuRoleEntity> {

    @Autowired
    RedisUtils redis;

    public List<MinReource> resources() {
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveRoleMenus(Long roleId, List<Long> menuIdList) {
        if (menuIdList != null) {
            this.remove(Wrappers.lambdaQuery(MenuRoleEntity.class).eq(MenuRoleEntity::getRoleId, roleId));
            if (!menuIdList.isEmpty()) {
                final List<MenuRoleEntity> entities = menuIdList.stream()
                        .map(m -> {
                            return new MenuRoleEntity(roleId, m);
                        })
                        .collect(Collectors.toList());
                return this.saveBatch(entities);
            }
        }
        return false;
    }

    /**
     * 检查配置菜单边界（添加的菜单项不能超过当前用户已拥有的菜单项）
     * @return: boolean
     * @author: fengt
     * @date: 2021/7/21 15:08
     **/
    public boolean checkBounds(List<Long> menuIdList) {
        if (menuIdList == null || menuIdList.isEmpty()) {
            return false;
        }

        final Long userId = ShiroUtils.getUser().getId();
        if (UserConst.SUPER_USERS.contains(userId)) {
            return false;
        }

        List<Long> menus = this.baseMapper.getMenuIdsByUserId(userId);
        if (menus.isEmpty()) {
            return true;
        } else {
            return !menus.containsAll(menuIdList);
        }
    }
}

